package com.fingard.dsp.bank.directbank.dlcb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 大连银行批量代收付
 * <p>
 * 参考文档：
 * 大连银行银企直联企业对接交易接口(部分)v1.0.2.docx
 * 代发代扣明细查询.docx
 *
 * @author Cruise
 * @date 2018/11/06
 */
public class DLCB01BatPayRec extends DLCB01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    /**
     * 批量代收付提交
     * <p>
     * 支持接口：
     * 2.2.2批量对外转账 �C416B300006
     * 2.3.3	批量代扣 �C416B300017
     *
     * @param p_reqBat
     * @return
     * @throws Exception
     */
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        try {
            DLCB01Header tmpBankHeader = new DLCB01Header();
            tmpBankHeader.isFile = "1";
            String commandCode = p_reqBat.reqHeader.commandCode;
            if ("9188".equals(p_reqBat.reqHeader.transType)) {
                tmpBankHeader.trncode = "416B300017";
                //批量转账
            } else if ("198801".equals(commandCode)) {
                tmpBankHeader.trncode = "416B300006";
                //批量代发
            } else if ("198802".equals(commandCode)) {
                tmpBankHeader.trncode = "416B300002";
            }

            tmpBankHeader.reqSeqNo = p_reqBat.reqHeader.transSeqID;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            writeCommonHeader(xmlWriter, tmpBankHeader);

            xmlWriter.writeStartElement("body");
            if ("198801".equals(commandCode)) {
                xmlWriter.writeElementString("pay_acno", p_reqBat.ownAct);
                xmlWriter.writeElementString("pay_cur_code", "01");
                xmlWriter.writeElementString("pay_acname", p_reqBat.ownActName);
                xmlWriter.writeElementString("pay_accaddr", "");
                xmlWriter.writeElementString("batch_no", p_reqBat.reqBatchNO);
                xmlWriter.writeElementString("count", p_reqBat.totalNum);
                xmlWriter.writeElementString("amt", p_reqBat.totalAmt);
                xmlWriter.writeElementString("file_name", p_reqBat.reqBatchNO + ".dat");
                xmlWriter.writeElementString("purpose", p_reqBat.abstractATS);
                xmlWriter.writeElementString("postscript", p_reqBat.abstractATS);
                xmlWriter.writeElementString("delay_flag", "0");
            } else {
                if ("198802".equals(commandCode)) {
                    //批量代发
                    xmlWriter.writeElementString("pay_acno", p_reqBat.ownAct);
                    xmlWriter.writeElementString("pay_cur_code", "01");
                    xmlWriter.writeElementString("pay_acname", p_reqBat.ownActName);
                    xmlWriter.writeElementString("pay_accaddr", "");
                    xmlWriter.writeElementString("supply_item", "1001");
                    boolean enableReceiptType = getBankConfig().getValueAsBool("enableReceiptType");
                    if (enableReceiptType) {
                        String receiptType = getBankConfig().getValueAsString("receiptType");
                        if (StringHelper.isNullOrEmpty(receiptType)) {
                            receiptType = "0";
                        }
                        xmlWriter.writeElementString("reserved3", receiptType);
                    }
                } else {
                    //批量代收
                    xmlWriter.writeElementString("rcv_acno", p_reqBat.ownAct);
                    xmlWriter.writeElementString("rcv_cur_code", "01");
                    xmlWriter.writeElementString("rcv_acname", p_reqBat.ownActName);
                    xmlWriter.writeElementString("pay_acno", "");
                    xmlWriter.writeElementString("pay_cur_code", "");
                    xmlWriter.writeElementString("pay_acname", "");
                    xmlWriter.writeElementString("rcv_accaddr", "");
                    xmlWriter.writeElementString("supply_item", "2001");
                }
                xmlWriter.writeElementString("as_flag", "0");
                xmlWriter.writeElementString("as_acno", "");
                xmlWriter.writeElementString("as_acname", "");
                xmlWriter.writeElementString("amt", p_reqBat.totalAmt);
                xmlWriter.writeElementString("purpose", p_reqBat.abstractATS);
                //对账码+用途
                String usType = p_reqBat.abstractATS + "-" + p_reqBat.useType;
                if (usType.length() > 255) {
                    usType = usType.substring(0, 255);
                }
                xmlWriter.writeElementString("postscript", usType);
                xmlWriter.writeElementString("reserved3", "");
                xmlWriter.writeElementString("file_name", p_reqBat.reqBatchNO + ".dat");
                xmlWriter.writeElementString("field_num", "6");
                xmlWriter.writeElementString("record_num", p_reqBat.totalNum);
                xmlWriter.writeElementString("count", p_reqBat.totalNum);
                xmlWriter.writeElementString("vir_acno", "");
                xmlWriter.writeElementString("vir_acname", "");
                xmlWriter.writeElementString("batch_no", p_reqBat.reqBatchNO);
            }
            xmlWriter.writeEndDocument();
            ReqPayRecDetail detail = null;
            StringBuilder sbFileContent = new StringBuilder();
            if ("198801".equals(commandCode)) {
                List<String> params = new ArrayList<String>();
                sbFileContent.append("cert_type|cert_no|rcv_acno|rcv_cur_code|rcv_acname|rcv_accaddr|amt|as_flag|as_acno|as_acname|rcv_bank_no|rcv_bank_name|bank_flag|area_flag|urgency_flag|purpose|postscript|booking_flag|booking_date|booking_time|mobiles|saverecvinfo_flag|");
                while (p_reqBat.readRecord()) {
                    detail = p_reqBat.readedDetail;
                    if (sbFileContent.length() > 0) {
                        sbFileContent.append("\r\n");
                    }
                    params.clear();
                    params.add("");//凭证类型 10 O
                    params.add(p_reqBat.readedDetail.askNumber);//凭证号 30 M
                    params.add(detail.recAct);//收款账号 C35 M
                    params.add("01");//收款币种 2 M
                    params.add(detail.recName);//收款户名 70 M
                    params.add("");//收款地址255 O
                    params.add(detail.payAmount);//金额 16,2 M
                    params.add("0");//是否使用账簿  0-不需要 1-需要
                    params.add("");//账簿号 38 O
                    params.add("");//账簿名 70 O
                    params.add(detail.cnapsCode);//收款行号 12 O
                    params.add(detail.cnapsName);//收款行名 70 O
                    params.add("1".equals(detail.sameBnk) ? "0" : "1");//跨行标志 0-本行 1-他行
                    params.add("1".equals(detail.sameCity) ? "0" : "1");// 同城异地 0-同城 1-异地
                    params.add("1".equals(detail.paySpd) ? "1" : "0");//加急标志 0-不加急 1-加急
                    //对账码+用途
                    String usType = detail.abstractATS + "-" + detail.useType;
                    if (usType.length() > 60) {
                        usType = usType.substring(0, 60);
                    }
                    params.add(usType);//用途  60 M
                    params.add(p_reqBat.readedDetail.askNumber);//附言  255 O
                    params.add("");//空或0时，都表示不预约。
                    params.add("");//预约日期 8
                    params.add("");//预约时间 6
                    params.add("");//手机 
                    params.add("1");//是否保存收款方信息  0－不保存  1－保存

                    //每笔明细:  凭证类型|凭证号|收款账号|收款币种|收款户名|收款地址|金额|
                    // 账簿标志|付款账簿号|付款账簿名|收款行号|收款行名|跨行标志|同城异地|
                    // 加急标志|用途|附言|预约标志|预约日期|预约时间|是否保存收款方信息|
                    StringBuilder sb = new StringBuilder("");
                    for (String param : params) {
                        sb.append(param).append("|");
                    }
                    sbFileContent.append(sb.toString());
                }
            } else {
                sbFileContent.append("ACNO|CUR_CODE|ACNAME|CARDFLAG|AMT|POSTSCRIPT|");
                while (p_reqBat.readRecord()) {
                    if (sbFileContent.length() > 0) {
                        sbFileContent.append("\r\n");
                    }
                    String oppAct = "";
                    String oppName = "";
                    //198802批量代发
                    if ("198802".equals(commandCode)) {
                        oppAct = p_reqBat.readedDetail.recAct;
                        oppName = p_reqBat.readedDetail.recName;
                    } else {
                        oppAct = p_reqBat.readedDetail.payAct;
                        oppName = p_reqBat.readedDetail.payName;
                    }
                    String payAmt = p_reqBat.readedDetail.payAmount;
                    String postScript = p_reqBat.readedDetail.askNumber + "-" + p_reqBat.readedDetail.abstractATS;
                    // 每笔明细: 付款账号|付款币种|付款户名|借贷标志|金额|附言|
                    String tmpReqBodyDetail = MessageFormat.format("{0}|01|{1}|0|{2}|{3}|", oppAct, oppName, payAmt, postScript);
                    sbFileContent.append(tmpReqBodyDetail);
                }
            }

            WriteBankLogLn2("批次明细文件内容:\r\n" + sbFileContent.toString());
            String tmpLocalMarkPath = StringHelper.trimEnd(bankFront.folderForRemoteHost, File.separator) + File.separator + p_reqBat.reqBatchNO + ".dat";
            WriteBankLogLn2("批次明细文件写入本机路径: " + tmpLocalMarkPath);

            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }

            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//            String[] tmpStrRet = new String[]{"", ""};
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetMsg = tmpBkReader.getFirstText("/ap/head/ret_info");
                    String tmpExtMsg = tmpBkReader.getFirstText("/ap/head/ext_info");
                    retAts.respInfo = StringHelper.joinNotEmpty("+", tmpRetMsg, tmpExtMsg);
                    retAts.respCode = "0";
                    retAts.transState = StringHelper.joinNotEmpty("+", tmpSuccFlag, tmpRetCode);
                    retAts.payInfoCode = tmpRetCode;
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (ConnState.FAIL.equals(tmpStrRet[0])) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.toString();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代收付状态查询
     * <p>
     * 支持接口：
     * 2.2.4批量对外转账查询 �C416B200112
     * 2.3.4	批量代扣查询 �C416B200207
     * 2.2.8批量对外转帐明细查询 -416B200202
     * 批量代扣明细查询 �C416B200208
     *
     * @param p_reqQryBat
     * @return
     * @throws Exception
     */
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            DLCB01Header tmpBankHeader = new DLCB01Header();
            String commandCode = p_reqQryBat.reqHeader.commandCode;
            if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                tmpBankHeader.trncode = "416B200207";
            } else if ("198801".equals(commandCode)) {
                tmpBankHeader.trncode = "416B200112";
            } else if ("198802".equals(commandCode)) {
                tmpBankHeader.trncode = "416B200100";
            }
            tmpBankHeader.reqSeqNo = p_reqQryBat.reqHeader.transSeqID;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            writeCommonHeader(xmlWriter, tmpBankHeader);

            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("cms_corp_no", bankFront.corpNo);
            xmlWriter.writeElementString("start_date", Format.Date8Format.format(p_reqQryBat.getBgnDateTime()));
            xmlWriter.writeElementString("end_date", Format.Date8Format.format(new Date()));
            xmlWriter.writeElementString("reserved2", "");
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetMsg = tmpBkReader.getFirstText("/ap/head/ret_info");
                    String file_flag = tmpBkReader.getFirstText("/ap/head/file_flag");
                    retAts.respCode = "0";
                    retAts.respInfo = tmpRetMsg;
                    retAts.transState = StringHelper.joinNotEmpty("+", tmpSuccFlag, tmpRetCode);
                    retAts.payInfoCode = tmpRetCode;

                    String totalNum = tmpBkReader.getFirstText("/ap/head/total");
                    String tmpSerialRecord = tmpBkReader.getFirstText("/ap/body/serial_record");
                    if (StringHelper.hasAnyChar(totalNum) && Integer.parseInt(totalNum) == 0) {
                        String totalBody = tmpBkReader.getFirstText("/ap/body/total");
                        String recordNumBody = tmpBkReader.getFirstText("/ap/body/record_num");
                        String fieldNumBody = tmpBkReader.getFirstText("/ap/body/field_num");
                        String[] fieldColumns = tmpSerialRecord.split("\\|");
                        if (Integer.parseInt(totalBody) == 0 && Integer.parseInt(recordNumBody) == 0 && Integer.parseInt(fieldNumBody) == fieldColumns.length) {
                            if (canBeNotExist(p_reqQryBat, retAts, 45)) {
                                retAts.respInfo = "记录不存在";
                                retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                retAts.transState = tmpRetCode + "+记录不存在";
                                retAts.payInfoCode = retAts.transState;
                                retAts.writeAfterDetail();
                                return retAts;
                            }
                        }
                    }

                    if ("0".equals(file_flag) || "1".equals(file_flag)) {
                        // 汇总信息
                        String tmpTotalContent = "";
                        boolean isContinue = false;

                        String serialNo = "";
                        if (StringHelper.hasAnyChar(tmpSerialRecord)) {
                            tmpTotalContent = tmpSerialRecord;
                            WriteBankLogLn2("当日交易数据内容:\r\n" + tmpTotalContent);

                            int count = 25;
                            if ("198801".equals(commandCode)) {
                                count = 22;
                            }

                            String[] tmpTotalArray = tmpTotalContent.split("\\|", -1);
                            int tmpTotalArrayLen = tmpTotalArray.length;
                            boolean isMatched = false;
                            for (int i = 0; i < tmpTotalArrayLen / count; i++) {
                                int baseNum = count * i;
                                String tmpReqSeqID = tmpTotalArray[1 + baseNum];
                                if (p_reqQryBat.reqBatchNO.equals(tmpReqSeqID)) {
                                    isMatched = true;
                                    // 汇总查询：0-成功;8-未知;1-失败;2-处理中
                                    //代付
                                    //serial_no|batch_no|acno|cur_code|acname|as_acno|as_acname|total_sum|amt|succ_count|succ_amt|
                                    // tr_acdt|tr_time|stat|cms_corp_no|corp_cn_name|user_no|user_name|summary|reserved1|reserved2|reserved3|
                                    // 994103|18112801066190|147205209000579|01|捷信消连连连连连公司|||2|7500.00|2|7500.00|
                                    // 20181120|111523|0|10000786|捷信消连连连连连公司|000001|白连蕊||38112801023350|||
                                    //代收
                                    //serial_no|batch_no|acno|cur_code|acname|item_typeno|item_name|total_sum|
                                    // amt|succ_count|succ_amt|tr_acdt|
                                    // tr_time|stat|cms_corp_no|corp_cn_name|user_no|user_name|summary|host_batchno|
                                    // reserved1|reserved2|reserved3|as_acno|as_acname|
                                    String tmpBatStatus = tmpTotalArray[13 + baseNum];
                                    if ("0".equals(tmpBatStatus) || "6".equals(tmpBatStatus)) {
                                        isContinue = true;
                                        serialNo = tmpTotalArray[baseNum];
                                        break;
                                    } else {
                                        retAts.transState = StringHelper.joinNotEmpty("+", tmpSuccFlag, tmpBatStatus);
                                        retAts.payInfoCode = retAts.transState;
                                        break;
                                    }
                                }
                            }

                            if (!isMatched) {
                                if (canBeNotExist(p_reqQryBat, retAts, 45)) {
                                    retAts.respInfo = "记录不存在";
                                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                    retAts.transState = tmpRetCode + "+记录不存在";
                                    retAts.payInfoCode = retAts.transState;
                                    retAts.writeAfterDetail();
                                    return retAts;
                                }
                            }
                        } else {
                            String tmpResultFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                            tmpTotalContent = FileHelper.readFileText(StringHelper.trimEnd(bankFront.folderForRemoteHost, File.separator) + File.separator + tmpResultFileName, getCharset());
                            WriteBankLogLn2("当日交易数据内容:\r\n" + tmpTotalContent);

                            StringReader strReader = new StringReader(tmpTotalContent);
                            BufferedReader tmpReader = new BufferedReader(strReader);
                            tmpReader.readLine();

                            while (true) {
                                String eachline = tmpReader.readLine();
                                if (eachline == null) {
                                    break;
                                }
                                if (eachline.indexOf("|") > 0) {
                                    String[] bodyValues = eachline.split("\\|", -1);
                                    if (p_reqQryBat.reqBatchNO.equals(bodyValues[1])) {
                                        // 汇总查询：0-成功;8-未知;1-失败;2-处理中
                                        //6是失败
                                        String tmpBatStatus = bodyValues[13];
                                        if ("0".equals(tmpBatStatus) || "6".equals(tmpBatStatus)) {
                                            isContinue = true;
                                            serialNo = bodyValues[0];
                                            break;
                                        } else {
                                            retAts.transState = StringHelper.joinNotEmpty("+", tmpSuccFlag, tmpBatStatus);
                                            retAts.payInfoCode = retAts.transState;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (isContinue) {
                            // 下载明细
                            if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                                tmpBankHeader.trncode = "416B200208";
                            } else if ("198801".equals(commandCode)) {
                                tmpBankHeader.trncode = "416B200202";
                            } else if ("198802".equals(commandCode)) {
                                tmpBankHeader.trncode = "416B200201";
                            }

                            xmlWriter = new XmlTextWriter();
                            xmlWriter.autoFormat = false;
                            writeCommonHeader(xmlWriter, tmpBankHeader);
                            xmlWriter.writeStartElement("body");
                            xmlWriter.writeElementString("cms_corp_no", bankFront.corpNo);
                            xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(p_reqQryBat.getBgnDateTime()));
                            xmlWriter.writeElementString("serial_no", serialNo);
                            xmlWriter.writeElementString("batch_no", p_reqQryBat.reqBatchNO);
                            xmlWriter.writeEndDocument();

                            tmpStrRet = sendToBank(xmlWriter.toXmlString());
                            if (tmpStrRet[0].length() == 0) {
                                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                                    tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                                    tmpRetMsg = tmpBkReader.getFirstText("/ap/head/ret_info");
                                    retAts.respCode = "0";
                                    retAts.respInfo = tmpRetMsg;
                                    retAts.transState = StringHelper.joinNotEmpty("+", tmpSuccFlag, tmpRetCode);
                                    retAts.payInfoCode = tmpRetCode;
                                    if ("0".equals(tmpSuccFlag) && "0000".equals(tmpRetCode)) {
                                        String tmpResultStr = "";
                                        if (StringHelper.hasAnyChar(tmpBkReader.getFirstText("/ap/body/serial_record"))) {
                                            tmpResultStr = tmpBkReader.getFirstText("/ap/body/serial_record");
                                            WriteBankLogLn2("当日明细结果文件内容:\r\n" + tmpResultStr);

                                            if ("198802".equals(p_reqQryBat.reqHeader.commandCode) || "918801".equals(p_reqQryBat.reqHeader.commandCode)) {
                                                List<String> tmpList = getResult(tmpResultStr);
                                                Iterator<String> lists = tmpList.iterator();
                                                while (lists.hasNext()) {
                                                    String eachLine = lists.next();
                                                    if (eachLine.contains("seqno")) {
                                                        continue;
                                                    }
                                                    String[] eachArray = eachLine.split("\\|");

                                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                                    // 每笔明细:0序号C（6）|1账号（20）|2币种C（2）|3户名C（70）|4借贷标志C(1)|
                                                    // 5金额N(18,2)|6备注C(70)|7交易日期C（8）|8交易时间C（8）|9状态（1）|10交易信息C（70）|11批次号C（20）|
                                                    String oppAct = eachArray[1];
                                                    String oppNm = eachArray[3];
                                                    if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                                                        tmpRetDetail.payAct = oppAct;
                                                        tmpRetDetail.payName = oppNm;
                                                    } else {
                                                        tmpRetDetail.recAct = oppAct;
                                                        tmpRetDetail.recName = oppNm;
                                                    }
                                                    tmpRetDetail.payAmount = eachArray[5];
                                                    String postScript = eachArray[6];
                                                    tmpRetDetail.postScript = postScript;
                                                    if (postScript.contains("-")) {
                                                        tmpRetDetail.postScript = postScript.substring(0, postScript.indexOf("-"));
                                                    }
                                                    tmpRetDetail.result = "0+" + eachArray[9];
                                                    String errorMsg = eachArray[10];
                                                    if ("9".equals(eachArray[9]) && "".equals(errorMsg)) {
                                                        errorMsg = "交易成功";
                                                    }
                                                    tmpRetDetail.payInfoCode = tmpRetDetail.result + "+" + errorMsg;
                                                    tmpRetDetail.memo = errorMsg;
                                                    retAts.writeRetDetail(tmpRetDetail);
                                                }
                                            } else {
                                                String[] tmpTotalArray = tmpResultStr.split("\\|", -1);
                                                int tmpTotalArrayLen = tmpTotalArray.length;
                                                int count = 12;

                                                if ("198801".equals(commandCode)) {
                                                    count = 30;
                                                }

                                                for (int i = 1; i < tmpTotalArrayLen / count; i++) {
                                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                                    //付款明细
                                                    //batch_no|serial_no|tr_acdt|tr_time|cert_no|pay_acno|pay_cur_code|pay_acname|
                                                    // as_acno|as_acname|bank_flag|area_flag|urgency_flag|rcv_acno|rcv_cur_code|rcv_acname|rcv_bank_no|
                                                    // rcv_bank_name|opp_mobiles|amt|booking_flag|booking_date|booking_time|purpose|
                                                    // postscript|stat|error_info|seqno|err_msg|summary|
                                                    //0批次号C(20)|1流水号C(8)|2交易日期C(8)|3交易时间 C(8)|4凭证号C(30)| 5账号C(35)|6币种C(2)|
                                                    // 7户名C(70)|8账簿号 C（8）|9账簿名称 C（70）|10跨行标志C（2）|同城异地C（2）|加急标志C（2）|
                                                    // 13收款账号C（35）|14收款币种C(2)|15收款户名C(70)|16收款行号C（30）|收款行名C(70)|对方电话C（30）
                                                    // |19金额N(18,2)| 20预约标志C（2）|预约日期C（8）|预约时间C（8）
                                                    // |23用途C（255）|24附言C(255)|25状态C（2）|26错误信息C（255）|现管流水号C（8）
                                                    // |错误描述C（255）|摘要C（255）|
                                                    int baseNum = count * i;
                                                    if ("198801".equals(commandCode)) {
                                                        tmpRetDetail.recAct = tmpTotalArray[13 + baseNum];
                                                        tmpRetDetail.recName = tmpTotalArray[15 + baseNum];
                                                        tmpRetDetail.payAmount = tmpTotalArray[19 + baseNum];
                                                        tmpRetDetail.postScript = tmpTotalArray[24 + baseNum];
                                                        //0 等待复核 1已作废 2等待审批 3 等待落地处理 4 等待提交 5已提交，等待相应
                                                        //6 交易失败 7已撤销 8 结果未知，待查询 9 交易成功 A 等待银行审批 B交易异常 C 交易预约
                                                        tmpRetDetail.result = "0+" + tmpTotalArray[25 + baseNum];
                                                        String errorMsg = tmpTotalArray[26 + baseNum];
                                                        if ("9".equals(tmpTotalArray[26 + baseNum]) && "".equals(errorMsg)) {
                                                            errorMsg = "交易成功";
                                                        }
                                                        tmpRetDetail.payInfoCode = tmpRetDetail.result + "+" + errorMsg;
                                                        tmpRetDetail.memo = errorMsg;
                                                        retAts.writeRetDetail(tmpRetDetail);
                                                    } else {
                                                        // 每笔明细:0序号C（6）|1账号（20）|2币种C（2）|3户名C（70）|4借贷标志C(1)|
                                                        // 5金额N(18,2)|6备注C(70)|7交易日期C（8）|8交易时间C（8）|9状态（1）|10交易信息C（70）|11批次号C（20）|
                                                        String oppAct = tmpTotalArray[1 + baseNum];
                                                        String oppNm = tmpTotalArray[3 + baseNum];
                                                        if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                                                            tmpRetDetail.payAct = oppAct;
                                                            tmpRetDetail.payName = oppNm;
                                                        } else {
                                                            tmpRetDetail.recAct = oppAct;
                                                            tmpRetDetail.recName = oppNm;
                                                        }
                                                        tmpRetDetail.payAmount = tmpTotalArray[5 + baseNum];
                                                        String postScript = tmpTotalArray[6 + baseNum];
                                                        tmpRetDetail.postScript = postScript;
                                                        if (postScript.contains("-")) {
                                                            tmpRetDetail.postScript = postScript.substring(0, postScript.indexOf("-"));
                                                        }
                                                        tmpRetDetail.result = "0+" + tmpTotalArray[9 + baseNum];
                                                        String errorMsg = tmpTotalArray[10 + baseNum];
                                                        if ("9".equals(tmpTotalArray[9 + baseNum]) && "".equals(errorMsg)) {
                                                            errorMsg = "交易成功";
                                                        }
                                                        tmpRetDetail.payInfoCode = tmpRetDetail.result + "+" + errorMsg;
                                                        tmpRetDetail.memo = errorMsg;
                                                        retAts.writeRetDetail(tmpRetDetail);
                                                    }
                                                }
                                            }
                                        } else {
                                            String tmpDetailFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                                            tmpResultStr = FileHelper.readFileText(StringHelper.trimEnd(bankFront.folderForRemoteHost, File.separator) + File.separator + tmpDetailFileName, getCharset());
                                            WriteBankLogLn2("当日明细结果文件内容:\r\n" + tmpResultStr);

                                            StringReader strReader = new StringReader(tmpResultStr);
                                            BufferedReader tmpReader = new BufferedReader(strReader);
                                            tmpReader.readLine();

                                            while (true) {
                                                String eachline = tmpReader.readLine();
                                                if (eachline == null) {
                                                    break;
                                                }
                                                if (eachline.indexOf("|") > 0) {
                                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                                    String[] bodyValues = eachline.split("\\|", -1);

                                                    if ("198801".equals(commandCode)) {
                                                        tmpRetDetail.recAct = bodyValues[13];
                                                        tmpRetDetail.recName = bodyValues[15];
                                                        tmpRetDetail.payAmount = bodyValues[19];
                                                        tmpRetDetail.postScript = bodyValues[24];
                                                        tmpRetDetail.result = "0+" + bodyValues[25];
                                                        String errorMsg = bodyValues[26];
                                                        if ("9".equals(bodyValues[25]) && "".equals(errorMsg)) {
                                                            errorMsg = "交易成功";
                                                        }
                                                        tmpRetDetail.payInfoCode = tmpRetDetail.result + "+" + errorMsg;
                                                        tmpRetDetail.memo = errorMsg;
                                                        retAts.writeRetDetail(tmpRetDetail);
                                                    } else {
                                                        // 每笔明细:序号C（6）|账号（20）|币种C（2）|3户名C（70）|4借贷标志C(1)|5金额N(18,2)|6备注C(70)|7交易日期C（8）|8交易时间C（8）|9状态（1）|10交易信息C（70）|11批次号C（20）|
                                                        String oppAct = bodyValues[1];
                                                        String oppNm = bodyValues[3];
                                                        if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                                                            tmpRetDetail.payAct = oppAct;
                                                            tmpRetDetail.payName = oppNm;
                                                        } else {
                                                            tmpRetDetail.recAct = oppAct;
                                                            tmpRetDetail.recName = oppNm;
                                                        }
                                                        tmpRetDetail.payAmount = bodyValues[5];
                                                        tmpRetDetail.postScript = bodyValues[6];
                                                        String postScript = bodyValues[6];
                                                        tmpRetDetail.postScript = postScript;
                                                        if (postScript.contains("-")) {
                                                            tmpRetDetail.postScript = postScript.substring(0, postScript.indexOf("-"));
                                                        }
                                                        tmpRetDetail.result = "0+" + bodyValues[9];
                                                        String errorMsg = bodyValues[10];
                                                        if ("9".equals(bodyValues[9]) && "".equals(errorMsg)) {
                                                            errorMsg = "交易成功";
                                                        }
                                                        tmpRetDetail.payInfoCode = tmpRetDetail.result + "+" + errorMsg;
                                                        tmpRetDetail.memo = errorMsg;
                                                        retAts.writeRetDetail(tmpRetDetail);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = tmpSbMsg.toString();
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpStrRet[1];
                            }
                        } else {
                            //记录不存在
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "file_flag值有误";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}